<template>
	<view style="width: 100%;height: 100%;">
		<!-- 领券中心页面 -->
		<view><uni-status-bar></uni-status-bar></view>

		<view class="search-box flex-cn">
			<view class="navbar-left flex-cn" style=" flex: 1;" @click.stop="backHome">
				<view style="width:100rpx;text-align: center;"
					class="qh-rt-single feiIconfont icon-shouye1 navbar-back-icon"> </view>
			</view>

			<view style="
                    font-weight: 550;
                    height: 80rpx;
                    line-height: 80rpx;
                    font-size: 35rpx;
                    display: flex;
                    justify-content: center;
                    align-content: center;
                    flex: 1;
                    ">
				领券中心
			</view>
			<view style="width: 320rpx;flex: 1;"></view>
		</view>


		<view style="background-color: #f3f3f3;padding-top: 10rpx;height: 100vh;    overflow-y: auto;"
			class="couponBox1">
			<!-- 优惠券 -->
			<block>
				<block v-for="(item, index) in coupon" :key="index" :for-id="index">
					<view class="couponBg" :id="index" :data-btn="item.btn"
					:data-id="item.id" :data-goods_id="item.goods_id" @tap="Receive">
						<view class="iconfont iconyouhuiquan wxmericon" style="color:#ff8281;"></view>
						<view class="couponBox">
							<view class="left">
								<text>￥</text>
								<text>{{ item.reducemoney }}</text>
							</view>
							<view class="right">
								<text class="title">{{ item.coupon_name }}</text>
								<view class="cooupon-mj">
									<text>满{{ item.needmoney }}元使用</text>
								</view>
								<!-- <view class="stage">{{ item.reducemoney }}{{ item.deduction }}元</view> -->
								<view class="stage">
									<view>{{ item.deduction }}元抵{{ item.needmoney }}元</view>
								</view>
								<view :class="'Receive ' + item.bgColor"  :id="index" :data-btn="item.btn"
								:data-id="item.id" :data-goods_id="item.goods_id">{{ item.btn }}</view>
							</view>
						</view>
					</view>
				</block>

				<view v-if="coupon.length > 0" class="position flex-cn-cn" @click.stop="backHome" >
					<view class="foot flex-cn-cn" >
						<text>回到首页</text>
					</view>
				</view>
				<!-- <view v-if="!coupon" class="empty">暂无优惠券</view> -->
				<view v-if="!coupon" :style="containerStyle">
					<qh-empty-data text="暂无优惠券~" width="238rpx" height="216rpx"
						:custom-style="{ marginTop: '40rpx' }"></qh-empty-data>
				</view>

				
				<view v-else class="nocoupon tips">此处优惠券仅供本店本商城使用</view>
				
			</block>

			
			<view class="couponBox_bottom"></view>

		</view>
	</view>
</template>

<script>
// pages/Coupon/Coupon.js
var app = getApp().globalData;

export default {
	data() {
		return {
			coupon: [],
			bgImg: "/static/images/coupon.png",
			btn: "",
			bgColor: "",
			mercoupon: [], //商家券
			payCoupon: [], //代金券
			nav: 1, //3微信商家券 1优惠券  4微信代金券
			page: 0,
			merpage: 0,
			payPage: 0,
			ismerCoupon: true, //有没有商家券权限
			isPayCoupon: true, //有没有微信代金券权限
			canload: true, //
			isloading: false,
			mercanload: true,
			paycanload: true,
			coupon_id: '',
			// shop_coupon_service: '', //1以获取服务商openid2未获取
			web_url: '', //
			service_status: "",
			ordinary_status: '',
			statusBarHeight: "",
			plugPermissionData: {},
			

		};
	 },

	components: {},
	props: {},
	computed: {
		containerStyle() {
			// 获取视口高度
			const viewportHeight = wx.getSystemInfoSync().windowHeight;
			const actualHeight = viewportHeight - 44 - 44 - 49;
			return `height: ${actualHeight}px; display: flex; align-items: center; justify-content: center;`;
		},
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		// #ifdef MP-ALIPAY
		if (JSON.stringify(options) == '{}') {
			options = my.getLaunchOptionsSync().query;
		}
		// #endif
		if (options && options.store_id) {
			this.$store.store_id = options.store_id;
		}
		// if(options.genre){
		// 	this.nav = options.genre	
		// }		

		let statusBarHeight = Number(getApp().globalData.XcxData.statusBarHeight) * 2;
		this.statusBarHeight = statusBarHeight + 'rpx';
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () { },

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: async function () {
		await this.$onLaunched;

		this.getServicePermissions();
		var that = this; //优惠券
		this.mercanload = true;
		this.canload = true;
		this.paycanload = true;
		this.isloading = false;
		this.page = 0;
		this.merpage = 0;
		this.payPage = 0;
		this.payCoupon = [];
		this.mercoupon = [];
		getApp().globalData.sendRequest({
			url: "/Plug/getPlugPermissions",
			data: {},
			success: res => {
				if (res.status == 1) {
					that.plugPermissionData = res.data.plug;
				}
			}
		});
		if (that.nav == 1) {
			that.getcoupan()
		} else {
			that.receivemercoupon()
		}
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () { },

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () { },
	onShareAppMessage(res) {
		console.log(res, '参数啊啊啊');
		return {
			title: '会员专享福利', // Custom share title
			imageUrl: 'https://safood-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/1735800052677634f48a605.png', // Custom share image URL
		};
	},
	onReachBottom() {
		console.log('加载更多', this.nav)
		if (this.nav == 1) {
			this.getcoupan()
		} else if (this.nav == 3 || this.nav == 4) {
			this.receivemercoupon()
		}
	},
	methods: {

		//后退
		backHome() {
			// uni.navigateBack();
			uni.navigateTo({
				url: '/pages/mer/tabbar/home/home'
			});
		},
		//是否通过服务商公众号获取到用户openid
		getServicePermissions() {
			let _this = this;
			getApp().globalData.sendRequest({
				url: "/My/getServiceOpenid",
				data: {},
				success: res => {
					if (res.status == 1) {
						// _this.shop_coupon_service = res.data.shop_coupon_service
						_this.service_status = res.data.service_status;
						_this.ordinary_status = res.data.ordinary_status
					}
				}
			})
		},

		//tab切换 3 商家券 1优惠券
		changeNav(nav) {
			this.nav = nav;
			this.page = 0;
			this.merpage = 0;
			this.payPage = 0;
			this.mercanload = true;
			this.canload = true;
			this.paycanload = true;
			if (nav == 1) {
				this.getcoupan()
			} else if (nav == 3 || nav == 4) {
				this.receivemercoupon()
			}
		},
		//获取优惠券
		getcoupan() {
			let that = this;
			if (that.canload) {
				let page = parseInt(that.page) + 1;
				getApp().globalData.sendRequest({
					url: '/ShiFu/getVipCouponList',
					type: "post",
					data: {
						// coupon_type: 1,
						page: page,
						store_id: 1
					},
					success: function (res) {
						if (res.status == 1) {
							console.log('11112')
							for (var i = 0; i < res.data.length; i++) {
								// 计算deduction值并保留两位小数
								res.data[i]['deduction'] = (res.data[i]['needmoney'] - res.data[i]['reducemoney']).toFixed(2);
								if (res.data[i]['is_collected'] == 0) {
									res.data[i]['bgImg'] = "/static/images/coupon.png";
									res.data[i]['btn'] = '立即领取';
									res.data[i]['bgColor'] = '';
								} else {
									res.data[i]['bgImg'] = "/static/images/coupon.png";
									res.data[i]['btn'] = '去使用';
									res.data[i]['bgColor'] = 'on';
								}
							}
							console.log(page)
							if (page == 1) {
								that.setData({
									coupon: res.data,
									page: page
								});
							} else { //加载更多
								let coupon = that.coupon;
								that.coupon = [...coupon, ...res.data]
								that.setData({
									page: page
								});
							}

							if (res.data.length < 10) {
								that.canload = false
							} else {
								this.canload = true
							}

						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 1500
							})
						}
					}
				})
			} else {
				console.log(that.canLoad)
				// uni.showToast({
				// 	title: "没有更多优惠券了",
				// 	icon: 'none',
				// 	duration: 1500
				// })
			}
		},

		// 立即领取-优惠券
		Receive(e) {
			console.log(e);
			var that = this;
			var id = e.currentTarget.id;
			var coupon_id = e.currentTarget.dataset.id;
			var coupon = this.coupon;
			let couponItem = this.coupon[id];
			let text = e.currentTarget.dataset.btn;
			let store_id = 1
			if (text == '立即领取') {
				uni.showModal({
					content: '确定领取该优惠劵吗？',
					showCancel: true,
					confirmColor: '#ff5c6d',
					success: function (res) {
						// console.log(res);
						if (res.confirm) {
							getApp().globalData.sendRequest({
								url: '/ShiFu/collectVipCoupon',
								type: "post",
								data: {
									coupon_id: coupon_id,
									store_id
								},
								success: function (res) {
									// console.log(res);
									if (res.status == 1) {
										// uni.navigateTo({
										// 	url: `/pages/mer/goods/search/search?mycoupon=2&goods_id_gather=${goods_id_gather}`
										// })
										uni.showToast({
											title: '领取成功',
											duration: 1500,
											mask: true,
											success: function (res) { },
											fail: function (res) { },
											complete: function (res) { }
										});
										couponItem.btn = '去使用';
										couponItem.bgColor = 'on';
										coupon[id] = couponItem
										that.setData({
											coupon: coupon,
											couponList: coupon
										}, function () {
											console.log('setData success');
										});
									} else {
										uni.showToast({
											title: '领取失败',
											duration: 1500,
											mask: true,
											success: function (res) { },
											fail: function (res) { },
											complete: function (res) { }
										});
									}


								}
							});
						}
					},
					fail: function (res) { },
					complete: function (res) { }
				});

			}else if (text == '去使用') {
				const goods_id = e.currentTarget.dataset.goods_id;
				uni.navigateTo({
					 url: `/pages/mer/goods/search/search?mycoupon=2&goods_id_gather=${goods_id}`
				})
			}
		},

		btnFun() {
			var coupon = this.coupon;

			for (var i = 0; i < coupon.length; i++) {
				coupon[i].btn = '立即领取', coupon[i].bgColor = '';
			}

			this.setData({
				coupon: coupon
			});
		},

		//领取微信代金券
		receivePayCoupon(id) {
			let _this = this;
			getApp().globalData.sendRequest({
				url: "/PayCoupon/receiveCoupon",
				type: "POST",
				data: {
					id: id,
					store_id: this.$store.mallStoreId
				},
				success: function (res) {

					if (res.status == 1) {
						uni.showToast({
							title: '领取成功',
							icon: 'success',
							duration: 2000
						})
						_this.payCoupon.forEach(function (item, index) {
							if (item.id == id) {
								item.isget = true
							}
						})
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 2000
						})
					}
				}
			})
		},

		//领取商家券,触发冒泡事件拿到该商家券的ID
		getcouponid(id) {
			this.coupon_id = id;
		},

		//获取商家券或者代金券列表
		receivemercoupon() {
			console.log('获取商家券列表')
			let that = this;
			let data = {},
				page;

			data.coupon_type = that.nav;
			if (that.nav == 3) {
				page = parseInt(that.merpage) + 1;
			} else if (that.nav == 4) {
				page = parseInt(that.payPage) + 1;
			}
			data.page = page;
			data.store_id = this.$store.mallStoreId
			if (that.mercanload || that.paycanload) {
				getApp().globalData.sendRequest({
					url: '/Coupon/coupons',
					type: "post",
					data: data,
					success: function (res) {
						// console.log(res);
						if (res.status == 1) {
							that.web_url = res.web_url;
							if (data.page == 1) {
								if (that.nav == 3) {

									let mercoupon = [...res.data];
									mercoupon.forEach(function (item, index) {
										item.isget = false
									})
									that.setData({
										mercoupon: mercoupon,
										merpage: page,

									});
								} else if (that.nav == 4) {
									let payCoupon = [...res.data];
									payCoupon.forEach(function (item, index) {
										item.isget = false
									})
									that.setData({
										payCoupon: payCoupon,
										payPage: page,

									});
								}

							} else { //加载更多
								if (that.nav == 3) {
									//商家券
									let mercoupon = that.mercoupon;
									let data = res.data;
									data.forEach(function (item, index) {
										item.isget = false
									})
									that.mercoupon = [...mercoupon, ...data]
									that.merpage = page
								} else if (that.nav == 4) {
									//代金券
									let payCoupon = that.payCoupon;
									let data = res.data;
									data.forEach(function (item, index) {
										item.isget = false
									})
									that.payCoupon = [...payCoupon, ...data]
									that.payPage = page
								}
							}
							if (that.nav == 3) {
								res.data.length < 10 ? that.mercanload = false : that.mercanload = true;
							} else {
								res.data.length < 10 ? that.paycanload = false : that.paycanload = true;
							}

						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
								duration: 1500
							})
							if (that.nav == 3) {
								that.setData({
									mercoupon: null
								});
							} else if (that.nav == 4) {
								that.setData({
									payCoupon: null
								});
							}

						}
					}
				});
			} else {
				console.log()
				uni.showToast({
					title: "没有更多券了",
					icon: 'none',
					duration: 1500
				})
			}

		},

		//领券后调用的事件-微信商家券
		getcoupons(params) {
			let _this = this;
			if (params.detail.send_coupon_result[0].code == "SUCCESS") {
				getApp().globalData.sendRequest({
					url: '/ShopCoupon/receiveCouponCallback',
					type: "post",
					data: {
						coupon_id: _this.coupon_id,
						stock_id: params.detail.send_coupon_result[0].stock_id,
						coupon_code: params.detail.send_coupon_result[0].coupon_code,
						store_id: this.$store.mallStoreId

					},
					success: function (res) {
						uni.showToast({
							title: params.detail.send_coupon_result[0].message,
							duration: 2000
						});
					}
				});
				_this.mercoupon.forEach(function (item, index) {
					if (item.id == _this.coupon_id) {
						item.isget = true
					}
				})
			} else {
				uni.showToast({
					title: params.detail.send_coupon_result[0].message,
					icon: 'none',
					duration: 2000
				});

			}
		},
		//手动返回上一页
		// backFront() {
		// 	uni.navigateBack({
		// 		delta: 1
		// 	})
		// },
		//跳转公众号
		showAccount(type) {
			// + '&xcx_id=1' + 
			let userInfo = uni.getStorageSync('userInfo');
			let uid = userInfo.uid;
			let backPage = getCurrentPages();
			let page = (backPage[backPage.length - 1]).route.toString()
			console.log('this.web_url', userInfo, this.web_url)
			uni.navigateTo({
				url: '../web/web?url=' + this.web_url + '&uid=' + uid + '&page=' + page + '&user_type=' + type
			})
		},

		//部分商品可以用-查看
		toProductList(good_id, store_id) {
			let goods_id_gather = good_id;
			let coupon_type = this.nav == 3 ? 3 : 4;
			uni.navigateTo({
				url: "../../product/productList/productList?goods_id_gather=" + goods_id_gather +
					'&coupon_type=' + coupon_type + '&store_id=' + store_id
			})
		},
		//查看优惠券详情
		toCouponDetail(id, isget, genre) {
			//genre==2 微信代金券 genre==3微信商家券
			uni.navigateTo({
				url: "../merCouponDetail/merCouponDetail?id=" + id + '&type=1' + '&isget=' + isget +
					'&genre=' + genre
			})
		},
		toUse() {
			uni.showToast({
				title: '去使用',
				icon: 'none',
				duration: 1500
			})
		}
	}
};
</script>
<style>
@import "./coupon.css";

.foot {
	/* background: linear-gradient(to right, #ff948a, #ff5c6d); */
	background-color: #ff8281;
	color: #fff;
	font-size: 30rpx;
	width: 50%;
	height: 90rpx;
	margin-left: 30rpx;
	border-radius: 50rpx;
	margin: 10rpx;
	margin-top: 30rpx;
}


.couponBox_bottom {

	height: 200rpx;
}


/* @import '../../common/iconfont.css'; */
.navigation-bar {
	width: 100%;
	height: 90rpx;
	/* padding-top: 60rpx; */
	background: #fff;
	display: flex;
	align-items: center;

}

.navigations {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}

.navs {
	width: 30%;
	height: 100%;
	line-height: 80rpx;
	font-size: 28rpx;
	color: #999;
	text-align: center;
	position: relative;
}

.nav-actived {
	color: #333;
	border-radius: 16rpx;
	/* border: 1px solid #76BE16; */
}

.back-icon {
	width: 20rpx;
	height: 32rpx;
	transform: rotateY(180deg);
	/* */
}

.underLine {
	width: 80rpx;
	height: 4rpx;
	border-radius: 4rpx;
	background-color: #76BE16;
	margin: 0 auto;
}

.navH {
	height: 72rpx;
}

.stage2 {
	font-size: 22rpx;
	color: #fff;
	width: 300rpx;
	margin-bottom: 10rpx;
}

.home-coupon-left-icon {
	width: 70rpx;
	height: 28rpx;
	font-size: 18rpx;
	color: #fff;
	/* 	background-image: url(../../../static/images/merCoupon-scene.png); */
	background-image: url(/static/images/merCoupon-scene.png);
	background-size: 100% 100%;
	text-align: center;
	line-height: 23rpx;
	margin-right: 6rpx
}

.wxmericon {
	color: #3fd8a3;
	font-size: 182rpx;
}

.use-btn {
    background: #ff8281 !important;
    color: #fff !important;
    margin-top: 10rpx;
}

</style>
